/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 *
 * @author hendro
 */
public class JPAUtil {
    private static final EntityManagerFactory factory;
    private static final ThreadLocal threadSession = new ThreadLocal();
    private static final ThreadLocal threadTransaction = new ThreadLocal();
    
    static {
        try {
            factory = Persistence.createEntityManagerFactory("elproPU");
            System.out.println("Ok");
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory failed. " + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static EntityManager getEntityManager() throws Exception {
        EntityManager em = (EntityManager) threadSession.get();
        try {
            if (em == null) {
                em = factory.createEntityManager();
                threadSession.set(em);
            }
        } catch (Exception ex) {
            throw ex;
        }
        return em;
    }

    public static void closeEntityManager() throws Exception {
        try {
            EntityManager em = (EntityManager) threadSession.get();
            threadSession.set(null);
            if (em != null && em.isOpen()) {
                em.close();
            }
        } catch (Exception ex) {
            throw ex;
        }
    }

    public static void beginTransaction() throws Exception {
        EntityTransaction tx = (EntityTransaction) threadTransaction.get();
        try {
            if (tx == null) {
                tx = getEntityManager().getTransaction();
                tx.begin();
                threadTransaction.set(tx);
            }
        } catch (Exception ex) {
            throw ex;
        }
    }

    public static void commitTransaction() throws Exception {
        EntityTransaction tx = (EntityTransaction) threadTransaction.get();
        try {
            if (tx != null && tx.isActive() && !tx.getRollbackOnly()) {
                tx.commit();
            }
            threadTransaction.set(null);
        } catch (Exception ex) {
            roolbackTransaction();
            throw ex;
        }
    }

    public static void roolbackTransaction() throws Exception {
        EntityTransaction tx = (EntityTransaction) threadTransaction.get();
        try {
            threadTransaction.set(null);
            if (tx != null && tx.isActive() && !tx.getRollbackOnly()) {
                tx.rollback();
            }
        } catch (Exception ex) {
            throw ex;
        } finally {
            closeEntityManager();
        }
    }
}
